<template>
  <a-card :bordered="false">
    <div style="margin-bottom:10px">
      <a-button icon="plus" type="primary" @click="handleAdd">新增品牌</a-button>
    </div>
    <div>
      <a-table
        ref="table"
        bordered
        size="middle"
        :loading="loading"
        :columns="columns"
        :dataSource="dataSource"
        rowKey="id"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <template slot="img" slot-scope="text,record,index">
          <div style="width:60px;height:60px;margin:0 auto">
            <img :src="record.img" alt style="width:100%;height:100%" />
          </div>
        </template>
        <template slot="action" slot-scope="text,record,index">
          <div>
            <a-button
              type="primary"
              icon="edit"
              @click="handleEdit(record)"
              style="margin-right:10px;"
            >编辑</a-button>
            <a-popconfirm
              placement="top"
              :title="confirm_title"
              @confirm="confirm(record)"
              okText="Yes"
              cancelText="No"
            >
              <a-button type="danger" icon="delete">删除</a-button>
            </a-popconfirm>
          </div>
        </template>
      </a-table>
    </div>
    <a-modal
      :title="modal_title"
      :visible="modal_visible"
      :confirmLoading="loading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form :form="form">
        <a-form-item label="ID" :labelCol="labelCol" :wrapperCol="wrapperCol" style="display:none">
          <a-input v-decorator="['id']" style="display:none" :disabled="true"></a-input>
        </a-form-item>
        <a-form-item label="品牌名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['name',{rules:[{required:true,message:'品牌名称'}]}]"></a-input>
        </a-form-item>
        <a-form-item label="图片" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-upload
            :action="modal_action"
            listType="picture-card"
            :fileList="fileList"
            @preview="handlePreview"
            @change="handleChange"
            :beforeUpload="beforeUpload"
            accept=".jpg, .png, .jpeg, .JPG, .PNG, .JPEG"
          >
            <div v-if="fileList.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">上传图片</div>
            </div>
          </a-upload>
          <!-- ,{rules:[{required:true,message:'请上传图片'}]} -->
          <a-input
            v-decorator="['img']"
            placeholder="图片"
            :disabled="true"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
import { postAction, baseUrl } from '@/api/manage.js'

export default {
  data() {
    return {
      columns: [
        { title: 'ID', align: 'center', dataIndex: 'id' },
        { title: '品牌', align: 'center', dataIndex: 'name', width: 200 },
        { title: 'Logo', align: 'center', scopedSlots: { customRender: 'img' } },
        { title: '操作', align: 'center', scopedSlots: { customRender: 'action' } }
      ],
      loading: false,
      dataSource: [],
      modal_title: '',
      modal_visible: false,
      form: this.$form.createForm(this), // 只有这样注册后，才能通过表单拉取数据
      pagination: {
        total: 0,
        pageSize: 10,
        current: 1,
        showTotal: total => `共有 ${total} 条数据` //分页中显示总的数据
      },
      labelCol: {
        lg: {
          span: 7
        },
        sm: {
          span: 7
        }
      },
      wrapperCol: {
        lg: {
          span: 10
        },
        sm: {
          span: 17
        }
      },
      modal_action: `${baseUrl}/file/uploadImg`,
      fileList: [],
      confirm_title: '确定要删除此类型?'
    }
  },
  created() {
    this.getData()
  },
  methods: {
    getData() {
      this.loading = true
      postAction('/brand/page', {
        page: this.pagination.current,
        size: this.pagination.pageSize
      }).then(res => {
        this.loading = false
        this.dataSource = res.data
        const pagination = { ...this.pagination }
        pagination.total = res.total
        this.pagination = pagination
      })
    },
    handleOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.loading = true
          let url = '/brand/add'
          //   if (this.modal_title == '新增品牌') {
          //     url = '/brand/add'
          //   } else if ((this.modal_title = '编辑品牌')) {
          //     url = '/brand/delete'
          //   }
          postAction(url, this.form.getFieldsValue()).then(res => {
            this.loading = false
            this.form.resetFields()
            this.modal_visible = false
            this.fileList = []
            this.getData()
            
          })
        }
      })
    },
    handleCancel() {
      this.fileList = []
      this.form.resetFields()
      this.modal_visible = false
    },
    handleAdd() {
      this.modal_title = '新增品牌'
      this.modal_visible = true
    },
    handleTableChange(pagination) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.getData()
    },
    handleEdit(item) {
      //   console.log(item)
      this.modal_title = '编辑品牌'
      const obj = {
        uid: '-1',
        name: 'xxx.png',
        status: 'done',
        url: item.img
      }
      this.fileList.push(obj)
      setTimeout(() => {
        this.form.setFieldsValue({
          id: item.id,
          name: item.name,
          img: item.img
        })
      })
      this.modal_visible = true
    },
    //点击预览图标时的回调
    handlePreview(file) {},
    //上传文件改变时的状态
    handleChange({ file, fileList }) {
      this.fileList = fileList
      if (file.status == 'done') {
        fileList = fileList.map(item => {
          this.form.setFieldsValue({
            img: item.response.data
          })
        })
      } else if (file.status == 'removed') {
        this.form.setFieldsValue({
          img: ''
        })
      }
    },
    confirm(item) {
      this.loading = true
      postAction('/brand/delete', {
        id: item.id
      }).then(res => {
        this.loading = false
        if (this.dataSource.length == 1) {
          if (this.page == 1) {
            this.page = 1
          } else {
            this.page--
          }
        }
        this.getData()
      })
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
      if (!isJPG) {
        this.$message.error('仅支持jpeg/png/jpg格式!')
      }
      // const isLt2M = file.size / 1024 / 1024 < 5
      // if (!isLt2M) {
      //   this.$message.error('上传不能超过5MB!')
      // }
      return isJPG
    }
  }
}
</script>

<style lang="scss" scoped>
</style>